package nl.twleaks.alice.tasks;

import static com.google.appengine.api.urlfetch.FetchOptions.Builder.doNotFollowRedirects;

import java.net.MalformedURLException;
import java.net.URL;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;

import nl.twleaks.alice.entities.User;
import nl.twleaks.alice.task.RequestTask;
import nl.twleaks.alice.task.Task;
import nl.twleaks.alice.task.TaskExecutor;

@SuppressWarnings("serial")
public class LoginSelectWorldTask extends RequestTask implements Task {
	
	Task task;
	public LoginSelectWorldTask(User user) {
		super(user);
		task = new LoginWorldTask(user);
	}
	
	@Override
	public void beforeExecute() {
		try {
			request = new HTTPRequest(new URL("http://www.tribalwars.nl/index.php?action=login&server_" + getUser().getServer()), HTTPMethod.POST, doNotFollowRedirects());
			request.setPayload(new String("user=" + getUser().getUsername() + "&password=" + get("hash")).getBytes());
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void afterExecute() {
		for(HTTPHeader header : response.getHeaders()) {
			if(header.getName().equals("Location")) {
				task.set("location", header.getValue());
			}
		}
	}

	@Override
	public void afterTask() {
		if(task.has("location")) {
			TaskExecutor.execute(task);
		}
	}
}
